package com.dunshan.dunshanlogback.config;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @author .dunshan
 * @program: dunshan-pef
 * @description: 跨域
 * @date 2021-10-09 17:35:23
 */
@Component
public class CrossInterceptor implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");//* 表示该资源谁都可以用,从而实现跨域
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
        HttpServletRequest request = (HttpServletRequest) req;

        try {
            chain.doFilter(req, res);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }

    /**
     * @author .dunshan
     * @program: dunshan-pef
     * @description: Filter
     * @date 2021-10-05 12:03:29
     */
    @Log4j2
    @Component
    public static class MdcLogEnhancerFilter implements HandlerInterceptor {


        public final static String REQUEST_ID = "traceId";

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            try {
//                String id = request.getParameter("id");
                String traceId = request.getHeader("traceId");
                if (StringUtils.isEmpty(traceId)) {
                    log.info("正常流量");
                } else {
                    String uuid = UUID.randomUUID().toString().replace("-", "");
                    MDC.put(REQUEST_ID, "yace");
                    log.info("压测流量");
                }

            } catch (Exception e) {
                // 捕捉异常，不可阻断流程，无需做任何处理
            }
            return true;
        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            //移除id
            MDC.remove(REQUEST_ID);
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        }
    }
}
